import time
import requests
from dao import SendHistorySDK,BlackListSDK
from PIL import Image
from io import BytesIO
from playwright.sync_api import sync_playwright


class JobScraper:
    def __init__(self):
        self.playwright = None
        self.browser = None
        self.page = None
        self.url = None
        self.black_list = self.get_black_list()

    def launch_browser(self):
        self.playwright = sync_playwright().start()
        self.browser = self.playwright.chromium.launch(headless=False)
        self.page = self.browser.new_page()

    def refresh_black_list(self):
        self.black_list = self.get_black_list()
        
    def get_black_list(self):
        companies = BlackListSDK.list_companies()
        return [company[1] for company in companies]

    def login_page(self):
        self.navigate_to_page("https://www.zhipin.com/web/user/?ka=header-login")
        self.page.wait_for_load_state('networkidle')
        self.page.query_selector(".wx-login-btn").click()
        self.page.wait_for_selector(".mini-qrcode")
        image_element = self.page.query_selector('.mini-qrcode')
        if image_element:
            src = image_element.get_attribute('src')
            # print(src)
            self.download_and_show_image(src)
        else:
            raise("微信登录二维码拉取失败")

    def navigate_to_page(self, url):
        self.page.goto(url)
        self.page.wait_for_load_state('load')  # 等待页面加载完成

    def download_and_show_image(self, url):
        response = requests.get(url)
        image = Image.open(BytesIO(response.content))
        image.show()

    def set_url(self,url):
        self.url = url

    def scrape_jobs(self,send_num):
        self.navigate_to_page(self.url)
        self.page.wait_for_selector('.rec-job-list', timeout=10000)  # 等待包含工作列表的ul元素加载
        for x in range(0, 5):
            self.page.evaluate('window.scrollTo(0, document.body.scrollHeight)')
            time.sleep(1)
        time.sleep(2)
        job_list = self.page.query_selector('.rec-job-list')
        job_elements = job_list.query_selector_all('li.job-card-box')  # 获取ul中的所有li元素
        for x in range(0, send_num):
            job_elements[x].hover()
            job_name = job_elements[x].query_selector('.job-name')
            company_name = job_elements[x].query_selector('.boss-name')
            job_name_text = job_name.text_content().strip()
            company_name_text = company_name.text_content().strip()
            flag = False
            for blank in self.black_list:
                if company_name_text in blank or blank in company_name_text:
                    flag = True
            if flag:
                # 黑名单跳过
                continue
            try:
                chat_button = self.page.query_selector('text="立即沟通"')
            except Exception as e:
                    print(f"等待'立即沟通'按钮超时: {e}")
                    continue
            if chat_button:
                chat_button.click()
            try:
                self.page.wait_for_selector('text="留在此页"', timeout=2000)
                stay_button = self.page.query_selector('text="留在此页"')
                if stay_button:
                    stay_button.click()
            except Exception as e:
                print(f"等待'留在此页'按钮超时: {e}")
                self.navigate_to_page(self.url)
                self.page.wait_for_selector('.rec-job-list', timeout=10000)  # 等待包含工作列表的ul元素加载
                for x in range(0, 5):
                    self.page.evaluate('window.scrollTo(0, document.body.scrollHeight)')
                time.sleep(2)
                job_list = self.page.query_selector('.rec-job-list')
                job_elements = job_list.query_selector_all('li.job-card-box')  # 获取ul中的所有li元素
                continue
            if job_name and company_name:
                SendHistorySDK.add_record(job_name_text,company_name_text,1)

            # specific_element = self.page.wait_for_selector('i.ui-icon-arrow-right', timeout=20000)
            # if specific_element:
            #     specific_element.click()

    def close_browser(self):
        self.browser.close()
        self.playwright.__exit__()

